# Copyright (c) 2009 by Alex Leone <acleone ~at~ gmail.com>
#
# This file is part of epp.
#
# epp is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# epp is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with epp.  If not, see <http://www.gnu.org/licenses/>.

r"""
Contains the [if(n)def] tag.

Syntax:
    [ifdef tagname:]
        statements
    [/ifdef tagname2:]
        (equivalent to else if tagname2)
    [/ifdef else:]
        else
    [/ifdef] (optional)

    Also for attributes:
    [ifdef !attr1:]
        ...

Examples:
    Note: s[1:] in p.parsetags(s[1:]) is to strip the leading '\n'
          from s

    >>> import epp
    >>> p = epp.Epp()
    >>> s = '''
    ... [ifdef tag1:]
    ...  tag1 is defined!
    ... [/ifdef else:]
    ...  tag1 is not defined!'''
    >>> print(p.parsetags(s[1:]))
    tag1 is not defined!
    >>> t = '[define tag1=""]'
    >>> print(p.parsetags(t + s[1:]))
    tag1 is defined!
    >>> s = '''
    ... [ifndef tag2:]
    ...  tag2 is not defined - defining tag2!
    ...  [define tag2=""]
    ... [ifndef tag2:]
    ...  tag2 is not defined!
    ... [/ifndef else:]
    ...  tag2 is defined!'''
    >>> print(p.parsetags(s))
    <BLANKLINE>
    tag2 is not defined - defining tag2!
    <BLANKLINE>
    tag2 is defined!
"""

import tags
from tags.tag import Tag

tagnames = ["ifdef", "ifndef"]

class Ifdef(Tag):

    def replace(self, eppinst, tagName, attrs):
        """
        If(not) defined.
        Returns: the result of parsing all the tags in the condition that
                is true.
        """
        isNDef = (tagName == 'ifndef')
        isDef = False
        for attrName, value in attrs:
            if attrName in eppinst._tags:
                isDef = True
            elif attrName.startswith('!'):
                attrName = attrName[1:]
                isDef = eppinst.hasDefinedAttr(attrName)
            if (isDef and not isNDef) or (not isDef and isNDef) or (attrName == 'else'):
                if value == None:
                    eppinst._print_message(
                            "Warning: [%s] %s should probably have a `:' or value"
                            % (tagName, attrName), 1)

                else:
                    return eppinst.parsetags(value)
        return ''